<?php
/***********************************************************
 * 文件管理
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller\system;
use app\admin\controller\Base;
use think\facade\Request;
use think\facade\Db;
use think\facade\Session;
class Uploadify extends Base
{
    //图库在线管理 - 左侧树形目录结构
    public function picture_folder()
    {
        $func       = input('func/s', '');
        $num        = input('num/d', 1);   
        $inputId    = input('inputId/s', '');
        $info = array(
            'num'      => $num,
            'func'     => $func,
            'inputId'  => $inputId,
        );
        $this->assign('info',$info);
        //侧边栏目录栏目
        $dirArr  = $this->getDir('uploads');
   
        $dirArr2 = [];
        foreach ($dirArr as $key => $val) {
            $dirArr2[$val['id']] = $val['dirpath'];
        }
        foreach ($dirArr as $key => $val) {
            $countFile = 0;
            $dirfileArr = glob("{$val['dirpath']}/*");
            if (empty($dirfileArr)) {
                empty($dirfileArr) && @rmdir($val['dirpath']);
                $dirArr[$key] = [];
                continue;
            }
            $dirfileArr2 = glob("{$val['dirpath']}/*.*"); // 文件数量
            $countFile = count($dirfileArr2);
            $dirname = preg_replace('/([^\/]+)$/i', '', $val['dirpath']);
            $arr_key = array_search(trim($dirname, '/'), $dirArr2);
            if (!empty($arr_key)) {
                $dirArr[$key]['pId'] = $arr_key;
            } else {
                $dirArr[$key]['pId'] = 0;
            }
            $dirArr[$key]['name'] = preg_replace('/^(.*)\/([^\/]+)$/i', '${2}', $val['dirpath']);
            !empty($countFile) && $dirArr[$key]['name'] .= "({$countFile})";
        }
        $zNodes = str_replace("\\/", "/", json_encode($dirArr,true));
        $this->assign('zNodes', $zNodes);
        return $this->fetch('picture_folder');
    }
    //图库在线管理 - 图片列表显示
    public function get_images_path($images_path = 'uploads')
    {
       if ('uploads' != $images_path && !preg_match('#^(uploads)/(.*)$#i', $images_path)) {
            $this->errorNotice('非法访问！');
        }
        $func = input('func/s');
        $num  = input('num/d','1');
        $info = array(
            'num'  => $num,
            'func' => empty($func) ? 'undefined' : $func,
        );
        $this->assign('info',$info);
        // 常用图片
        $common_pic = [];
        $arr1 = explode('/', $images_path);

        // 只有一级目录才显示常用图片
        if (1 >= count($arr1)) { 
            $common_pic = Db::name('common_pic')->order('id desc')->limit(16)->field('pic_path')->select()->toArray();
        }
        $this->assign('common_pic', $common_pic);
        $images_pic = Db::name('images')->order('id desc')->limit(16)->field('url')->select()->toArray();
        $this->assign('images_pic', $images_pic);
        
        // 图片列表
        $images_data = glob($images_path.'/*');
        $list = [];
        if (!empty($images_data)) {
            // 图片类型数组
            $image_type = tpCache('basic.image_type');
            $image_ext = str_replace('|', ',', $image_type);
            $image_ext = explode(",",$image_ext);
            // 处理图片
            foreach ($images_data as $key => $file) {
                $fileArr = explode('.', $file);    
                $ext = end($fileArr);
                $ext = strtolower($ext);
                if (in_array($ext, $image_ext)) {
                    $list[$key]['path'] = '/'.$file;
                    $list[$key]['time'] = @filemtime($file);
                }
            }
        }
        // 图片选择的时间从大到小排序
        $list_time = get_arr_column($list,'time');
        array_multisort($list_time,SORT_DESC,$list);

        // 返回数据
        $this->assign('list', $list);
        $this->assign('path_directory', $images_path);
        return $this->fetch();
    }
    //记录常用图片
    public function update_pic()
    {
        if(Request::isAjax()){
            $param = input('param.');
            if (!empty($param['images_array'])) {
                $where = '';
                $data  = []; 
                foreach ($param['images_array'] as $key => $value) {
                    // 删除条件
                    if ($key > 0) { 
                        $where .= ','; 
                    }
                    $where .= $value;
                    // 添加数组
                    $data[$key] = [
                        'pid' => md5($value),
                        'pic_path'    => $value,
                        'add_time'    => getTime(),
                        'update_time' => getTime(),
                    ];
                }
                $whereor = explode(",",$where);
                // 批量删除选中的图片
                Db::name('common_pic')->where('pic_path','IN',$whereor)->delete();
                // 批量添加图片
                if(!empty($data)){
                   Db::name('common_pic')->insertAll($data);
                } 
                // 查询最后一条数据
                $row = Db::name('common_pic')->field('id')->order('id', 'desc')->limit(20,1)->select()->toArray();
                if (!empty($row)) {
                    $id = $row[0]['id'];
                    // 删除ID往后的数据
                    Db::name('common_pic')->where('id','<',$id)->delete();
                }
            }
        }
    }
    //删除上传的图片
    public function delupload()
    {
        if (Request::isPost()) {
            return 1;
        }
    }
    /**
     * 提取上传图片目录下的所有图片
     * @param string $directory 目录路径
     * @param string $dir_name 显示的目录前缀路径
     * @param array $arr_file 是否删除空目录
     * @param num $num 数量
     */
    private function getDir($directory, &$arr_file = array(), &$num = 0) {
        $mydir = glob($directory.'/*', GLOB_ONLYDIR);
        $param = input('param.');
        if(!isset($param['func'])){
            $func='';
        }else{
            $func='&func='.$param['func'];
        }
        if(!isset($param['num'])){
            $pnum='';
        }else{
            $pnum='?num='.$param['num'];
        }
        $request = Request::instance();
        $domain = $request->baseFile().'/system.uploadify/get_images_path';
        if (0 <= $num) {
            $dirpathArr = explode('/', $directory);
            $level = count($dirpathArr);
            $open = (1 >= $level) ? true : false;
            $fileList = glob($directory.'/*');
            $total = count($fileList); // 目录是否存在任意文件，否则删除该目录
            if (!empty($total)) {
                $isExistPic = $this->isExistPic($directory);
                if (!empty($isExistPic)) {
                    $arr_file[] = [
                        'id'        => $num,
                        'url'       => $domain.$pnum.$func.'&images_path='.$directory,
                        'target'    => 'content_body',
                        'isParent'  => true,
                        'open'      => $open,
                        'dirpath'   => $directory,
                        'level'     => $level,
                        'total'     => $total,
                    ];
                }
            } else {
                @rmdir("$directory");
            }
        }
        if (!empty($mydir)) {
            foreach ($mydir as $key => $dir) {
                if (stristr("$dir/", 'uploads/soft_tmp/')) {
                    continue;
                }
                $num++;
                $dirname = str_replace('\\', '/', $dir);
                $dirArr  = explode('/', $dirname);
                $dir     = end($dirArr);
                $mydir2  = glob("$directory/$dir/*", GLOB_ONLYDIR);
                if(!empty($mydir2) AND ($dir != ".") AND ($dir != "..")){
                    $this->getDir("$directory/$dir", $arr_file, $num);
                }else if(($dir != ".") AND ($dir != "..")){
                    $dirpathArr = explode('/', "$directory/$dir");
                    $level = count($dirpathArr);
                    $fileList = glob("$directory/$dir/*"); // 目录是否存在任意文件，否则删除该目录
                    $total = count($fileList);
                    if (!empty($total)) {
                         // 目录是否存在图片文件，否则删除该目录
                        $isExistPic = $this->isExistPic("$directory/$dir");
                        if (!empty($isExistPic)) {
                            $arr_file[] = [
                                'id'        => $num,
                                'url'       => $domain.$pnum.$func.'&images_path='.$directory.'/'.$dir,
                                'target'    => 'content_body',
                                'isParent'  => false,
                                'open'      => false,
                                'dirpath'   => "$directory/$dir",
                                'level'     => $level,
                                'icon'      => $request->domain().'/common/plugins/ztree/css/zTreeStyle/img/dir_close.png',
                                'iconOpen'  => $request->domain().'/common/plugins/ztree/css/zTreeStyle/img/dir_open.png',
                                'iconClose' => $request->domain().'/common/plugins/ztree/css/zTreeStyle/img/dir_close.png',
                                'total'     => $total,
                            ];
                        }
                    } else {
                        @rmdir("$directory/$dir");
                    }
                }
            }
        }
        return $arr_file;
    }
    /**
     * 检测指定目录是否存在图片
     * @param string $directory 目录路径
     * @param string $dir_name 显示的目录前缀路径
     * @param array $arr_file 是否删除空目录
     * @return boolean
     */
    private function isExistPic($directory, $dir_name='', &$arr_file = [])
    {
        if (!file_exists($directory) ) {
            return false;
        }
        if (!empty($arr_file)) {
            return true;
        }
        //图片类型数组
        $image_type = tpCache('basic.image_type');
        $image_ext = str_replace('|', ',', $image_type);
        $image_ext = explode(",",$image_ext);
        $mydir = dir($directory);
        while($file = $mydir->read())
        {
            if((is_dir("$directory/$file")) AND ($file != ".") AND ($file != "..")){
                if ($dir_name) {
                    return $this->isExistPic("$directory/$file", "$dir_name/$file", $arr_file);
                } else {
                    return $this->isExistPic("$directory/$file", "$file", $arr_file);
                }
            }
            else if(($file != ".") AND ($file != "..")){
                $fileArr = explode('.', $file);    
                $ext = end($fileArr);
                $ext = strtolower($ext);
                if (in_array($ext, $image_ext)) {
                    if ($dir_name) {
                        $arr_file[] = "$dir_name/$file";
                    } else {
                        $arr_file[] = "$file";
                    }
                    return true;
                }
            }
        }
        $mydir->close();
        return $arr_file;
    }

}
